package com.emm.yixun.system.service.impl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.jws.WebService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.druid.util.StringUtils;
import com.emm.yixun.common.exception.ResponseCode;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.basic.service.ProjectPremisesService;
import com.emm.yixun.basic.service.ProjectService;
import com.emm.yixun.basic.service.UserProjectService;
import com.emm.yixun.basic.service.UserService;
import com.emm.yixun.common.model.Project;
import com.emm.yixun.common.model.ProjectPremises;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.UserProject;
import com.emm.yixun.common.model.ZNodes;
import com.emm.yixun.common.model.dto.ProjectDto;
import com.emm.yixun.common.model.dto.ProjectPremisesDto;
import com.emm.yixun.common.model.dto.UserProjectDto;
import com.emm.yixun.system.service.UserProjectServiceFacade;

@Service
@WebService(name="com.emm.yixun.system.service.UserProjectServiceFacade")
public class UserProjectServiceFacadeImpl implements UserProjectServiceFacade{
	private  final Logger   logger = LoggerFactory.getLogger(this.getClass()); 
	
	@Autowired
	private UserProjectService service;
	
	@Autowired
	private ProjectPremisesService premisesService;
	
	@Autowired
	private UserService userService;
	
	@Resource
	private ProjectService projectService;
	

	@Override
	public Response<UserProjectDto> save(UserProjectDto dto) {
		Response<UserProjectDto> response=new Response<UserProjectDto>();
		try {
			if(null==dto){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("保存"));
				return response;
			}
			if(dto.getUserId()!=null){
				UserProjectDto queryDto = new UserProjectDto();
				queryDto.setUserId(dto.getUserId());
				queryDto.setDelFlag("0");
				List<UserProject> userProject = service.selectListByDto(queryDto);
				for (UserProject user:userProject) {
					UserProjectDto destroy = new UserProjectDto();
					destroy.setId(user.getId());
					service.destroy(destroy);
				}
				List<String> projectList = new ArrayList<>();
				//保存新数据
				User user = userService.selectById(dto.getUserId());
				if(!StringUtils.isEmpty(dto.getAus())){
					String[] ausList = dto.getAus().split(","); 
					
					for (int i = 0; i < ausList.length; i++) {
						if(isMatching(ausList[i], "CHILDNODE_ID_*")){
							//得到组团
							String childNode=ausList[i].replace("CHILDNODE_ID_", "");
							ProjectPremises premises = premisesService.selectById(new Long(childNode));
							if(premises!=null){
								UserProjectDto saveDto= new UserProjectDto();
								saveDto.setMerchantId(user.getMerchantId());
								saveDto.setUserId(user.getId());
								saveDto.setAccessPath(premises.getProjectId()+","+premises.getId());
								saveDto.setAccessCode(premises.getId().toString());
								saveDto.setProjectId(premises.getProjectId());
								saveDto.setCreateUserId(dto.getCreateUserId());
								saveDto.setCreateTime(new Date());
								saveDto.setUpdateUserId(dto.getCreateUserId());
								saveDto.setUpdateTime(new Date());
								saveDto.setDelFlag("0");
								service.create(saveDto);
								projectList.add(premises.getProjectId().toString());
							}
						}
					}
					List<String> distinctList= distinct(ausList, projectList);
					for (int i = 0; i < distinctList.size(); i++) {
						
						if(!isMatching(distinctList.get(i), "CHILDNODE_ID_*")){
							UserProjectDto saveDto= new UserProjectDto();
							saveDto.setMerchantId(user.getMerchantId());
							saveDto.setUserId(user.getId());
							Project project = projectService.selectById(new Long(distinctList.get(i)));
							saveDto.setAccessPath(project.getId().toString());
							saveDto.setAccessCode(project.getId().toString());
							saveDto.setProjectId(project.getId());
							saveDto.setCreateUserId(dto.getCreateUserId());
							saveDto.setCreateTime(new Date());
							saveDto.setUpdateUserId(dto.getCreateUserId());
							saveDto.setUpdateTime(new Date());
							saveDto.setDelFlag("0");
							service.create(saveDto);
						}
					}
				}
			}
			response.success(dto);
			return response;
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("保存数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Response<Integer> updateByPrimaryKey(UserProjectDto dto,Boolean selective) {
		Response<Integer> response=new Response<Integer>();
		try {
			if(null==selective || null==dto || null==dto.getId()){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("更新"));
				return response;
			}
			
			if(selective){
				int count=service.update(dto);
				if(count>0){
					response.success(Integer.valueOf(count));
				}else{
					response.fail("90001", "更新数据失败");
				}
			}else{
				response.fail("90000", "暂未实现,修改参数selective=true即可");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("更新数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Response<Integer> deleteByPrimaryKey(Long id) {
		Response<Integer> response=new Response<Integer>();
		try {
			if(null==id){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("删除"));
				return response;
			}
			UserProjectDto mDto=new UserProjectDto();
			mDto.setId(id);
			int count=service.destroy(mDto);
			if(count>0){
				response.success(Integer.valueOf(count));
			}else{
				response.fail("90001", "删除数据失败");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("删除数据错误：{}",e);
		}
		return response;
	}
	
    @Override
	public Response<UserProject> findById(Long id) {
		Response<UserProject> response=new Response<UserProject>();
		try {
			if(null==id){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("主键查询"));
				return response;
			}
			UserProject entity=service.selectById(id);
			if(null==entity){
				response.fail("90001", "主键查询数据失败");
			}else{
				response.success(entity);;
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}",e);
		}
		return response;
	}

	@Override
	public ResponseList<UserProject> findByDto(UserProjectDto dto) {
		ResponseList<UserProject> response=new ResponseList<UserProject>();
		try {
			if(null==dto){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<UserProject> list=service.selectListByDto(dto);
			if(null==list){
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Page<UserProject> findPageByDto(UserProjectDto dto, Integer begin,Integer row) {
		Page<UserProject> response=new Page<UserProject>();
		try {
			if(null==dto || null==begin || null==row){
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			Page<UserProject> page = service.getPageModel(dto, begin, row);
			if(null==page.getRows()){
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			response=page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}",e);
		}
		return response;
	}
	
	/**
	* 方法描述 : 数组值 存在不存在
	* 创建者：ThinkPad 
	* 项目名称： emm-system
	* 类名： UserProjectServiceFacadeImpl.java
	* 版本： v1.0
	* 创建时间： 2016年6月1日 下午6:03:18
	* @param arr
	* @param targetValue
	* @return boolean
	 */
	public static boolean useList(String[] arr, String targetValue) {
		   return Arrays.asList(arr).contains(targetValue);
		}
	/**
	* 方法描述 : 通配
	* 创建者：ThinkPad 
	* 项目名称： emm-system
	* 类名： UserProjectServiceFacadeImpl.java
	* 版本： v1.0
	* 创建时间： 2016年6月1日 下午6:03:03
	* @param src
	* @param des
	* @return boolean
	 */
	public static boolean isMatching(String src, String des) {
		String des1 = des.replace("*", "\\w*");
		des1 = des1.replace("?", "\\w{1}");
		Pattern p = Pattern.compile(des1);
		Matcher m = p.matcher(src);
		return m.matches();
	}
	/**
	* 方法描述 : 去除数组中的重复值
	* 创建者：ThinkPad 
	* 项目名称： emm-system
	* 类名： UserProjectServiceFacadeImpl.java
	* 版本： v1.0
	* 创建时间： 2016年6月2日 上午9:44:12
	* @param aus
	* @param list
	* @return String[]
	 */
	public List<String> distinct(String[] aus , List<String> list){
		List<String> ausList = new ArrayList<>();
		Collections.addAll(ausList, aus);
		for (String p:list) {
			if(ausList.contains(p)){
				ausList.remove(p);
			}
		}
		return ausList;
	}

	@Override
	public ResponseList<ZNodes> anthorizedList(ProjectDto dto,Long userId) {
		ResponseList<ZNodes> listResponse=new ResponseList<ZNodes>();
		try {
			//组装Znodes
			List<ZNodes> list=new ArrayList<ZNodes>();
			//查询所有项目
			List<Project> response=projectService.selectListByDto(dto);
				for (Project project:response) {
					//添加父节点
					ZNodes znode=new ZNodes();
					znode.setId(project.getId().toString());
					znode.setName(project.getProjectName());
					//父节点是否选中
					UserProjectDto queryDto = new UserProjectDto();
					queryDto.setUserId(userId);
					queryDto.setProjectId(project.getId());
					queryDto.setDelFlag("0");
					List<UserProject> projectParent=service.selectListByDto(queryDto);
					if(projectParent!=null&&projectParent.size()>0){
						znode.setChecked("true");
					}else{
						znode.setChecked("false");
					}
					list.add(znode);
					//查询所有组团信息， 项目下面
					ProjectPremisesDto  premisesDto = new ProjectPremisesDto();
					premisesDto.setProjectId(project.getId());
					premisesDto.setDelFlag("0");
					List<ProjectPremises> ResponseList = premisesService.selectListByDto(premisesDto);
						for (ProjectPremises premises:ResponseList) {
							ZNodes childNodes=new ZNodes();
							childNodes.setId("CHILDNODE_ID_"+premises.getId().toString());
							childNodes.setName(premises.getGroupName());
							//子节点是否选中
							UserProjectDto childNodesDto = new UserProjectDto();
							childNodesDto.setUserId(userId);
							childNodesDto.setAccessCode(premises.getId().toString());
							childNodesDto.setDelFlag("0");
							List<UserProject> childNodesList=service.selectListByDto(childNodesDto);
							if(childNodesList!=null&&childNodesList.size()>0){
								childNodes.setChecked("true");
							}else{
								childNodes.setChecked("false");
							}
							childNodes.setpId(project.getId().toString());
							list.add(childNodes);
						}
					}
				listResponse.success(list);
					
		} catch (Exception e) {
			logger.error("anthorizedList error: ", e);
		}
		return listResponse;
	}

}
